<!-- 流程定义 -->
<template>
  <div>
    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="流程名称">
        <el-input v-model="searchForm.name" placeholder="请输入流程名称" />
      </el-form-item>
      <!-- <el-form-item label="开始时间">
        <el-date-picker
          v-model="searchForm.startTime"
          type="date"
          placeholder="选择开始时间"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="fetchList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="openEditor">新增流程定义</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="60" />
      <el-table-column prop="key" label="流程标识" />
      <el-table-column prop="name" label="流程名称" />
      <!-- <el-table-column prop="form" label="业务表单" /> -->
      <el-table-column prop="version" label="流程版本" />
      <el-table-column prop="suspended" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.suspended === false ? 'success' : 'warning'">{{ row.suspended ? '挂起' : '激活' }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="deployTime" label="部署时间" /> -->
      <el-table-column label="操作" width="350">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="viewDetail(row)">查看详情</el-button>
          <el-button size="small" type="success" @click="openFormConfig(row)">配置表单</el-button>
          <!-- <el-button size="small" @click="deploy(row)">部署</el-button> -->
          <el-button size="small" @click="toggleStatus(row)">
            {{ row.suspended === false ? '挂起' : '激活' }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteRow(row)">删除</el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增流程定义弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增流程定义">
      <!-- 这里放新增表单 -->
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="流程标识" prop="key">
          <el-input v-model="addForm.key" clearable/>
        </el-form-item>
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="addForm.name" clearable/>
        </el-form-item>
        <el-form-item label="流程描述">
          <el-input type="textarea" v-model="addForm.desc" :rows="10" />
        </el-form-item>
        <el-form-item label="流程模型" prop="modelId">
          <el-select v-model="addForm.modelId" placeholder="请选择流程模型" style="width: 100%">
            <el-option
              v-for="item in modelList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.version }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addProcess">确定</el-button>
      </template>
    </el-dialog>

    <!-- 配置表单弹窗 -->
    <el-dialog v-model="formConfigDialogVisible" title="配置表单" width="70%" style="margin-left: 300px;">
      <el-form :model="formConfig" label-width="100px">
        <el-form-item label="选择表单" prop="formId">
          <el-select 
            v-model="formConfig.formId" 
            placeholder="请选择表单" 
            style="width: 100%" 
            @change="handleFormChange"
            filterable
            :filter-method="filterForm"
            clearable
          >
            <el-option
              v-for="item in filteredFormList"
              :key="item.id"
              :label="item.formName"
              :value="item.id"
            >
              <span>{{ item.formName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                ID: {{ item.id }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表单预览" v-if="formConfig.formJson">
          <div class="form-preview">
            <v-form-render
              :key="formConfig.formId"
              :form-json="formConfig.formJson"
              :form-data="{}"
              :option-data="{}"
              :disabled="true"
              ref="vFormRef"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeFormConfig">取消</el-button>
        <el-button type="primary" @click="saveFormConfig">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { VFormRender } from 'vform3-builds'

export default {
  name: 'ProcessDefinition',
  components: {
    VFormRender
  },
  data() {
    return {
      searchForm: {
        name: '',
        startTime: null,
      },
      tableData: [], // 流程定义数据
      multipleSelection: [], // 多选
      addDialogVisible: false,
      addForm: {
        key: '',
        name: '',
        desc: '',
        modelId: '' // 改为存储模型ID
      },
      modelList: [], // 流程模型列表
      rules: {
        key: [
          { required: true, message: '请输入流程标识', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        modelId: [
          { required: true, message: '请选择流程模型', trigger: 'change' }
        ]
      },
      formConfigDialogVisible: false,
      formConfig: {
        processDefinitionId: '',
        formId: '',
        formJson: null
      },
      formList: [], // 表单列表
      filteredFormList: [], // 过滤后的表单列表
      currentRow: null, // 当前选中的行
    }
  },
  methods: {
    // 查询
    fetchList() {
      // TODO: 调用接口获取数据
      // this.tableData = await api.getProcessList(this.searchForm)
      this.$get('/findAllProcessDefinition',{
        name : this.searchForm.name
      }).then(res => {
        this.tableData = res.data
      }).catch(err => {
        console.log(err)
      })
    },
    // 重置
    resetSearch() {
      this.searchForm = { name: '', startTime: null }
      this.fetchList()
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取流程模型列表
    async fetchModelList() {
      try {
        // TODO: 调用获取流程模型列表接口
        // const response = await api.getModelList()
        // this.modelList = response.data
      } catch (error) {
        ElMessage.error('获取流程模型列表失败：' + error.message)
      }
    },
    // 新增
    openEditor() {
      this.$router.push('/workflow/processesManage/editor')
    },
    async addProcess() {
      try {
        await this.$refs.addFormRef.validate()
      } catch (error) {
        return
      }

      try {
        // TODO: 调用新增接口
        // const response = await api.addProcess({
        //   key: this.addForm.key,
        //   name: this.addForm.name,
        //   desc: this.addForm.desc,
        //   modelId: this.addForm.modelId
        // })
        ElMessage.success('新增成功')
        this.addDialogVisible = false
        this.fetchList()
      } catch (error) {
        ElMessage.error('新增失败：' + error.message)
      }
    },
    // 批量删除
    batchDelete() {
      this.$msgbox.confirm('确定要批量删除选中的流程定义吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 获取选中行的ID列表
        const processDefinitionIdList = this.multipleSelection.map(item => item.deploymentId)
        
        // 调用批量删除接口
        this.$post('/deleteProcessDefinition', processDefinitionIdList).then(res => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            this.fetchList()
          } else {
            ElMessage.error(res.message || '删除失败')
          }
        }).catch(err => {
          console.error(err)
        })
      })
    },
    deleteRow(row) {
      this.$msgbox.confirm('确定要删除选中的流程定义吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 获取选中行的ID列表
        if (row == null) {
          this.$message.error('删除的数据不能为空！')
          return
        }
        if(row.deploymentId == null || row.deploymentId == ''){
          this.$message.error('请选择要删除的数据！')
          return
        }
      
        let processDefinitionIdList = []
        processDefinitionIdList[0] = row.deploymentId
        
        // 调用批量删除接口
        this.$post('/deleteProcessDefinition', processDefinitionIdList).then(res => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            this.fetchList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        }).catch(err => {
          console.error(err)
        })
      })
    },
    // 部署
    deploy(row) {
      // TODO: 调用部署接口
      ElMessage.success('部署成功')
      this.fetchList()
    },
    // 激活/挂起
    toggleStatus(row) {
      // TODO: 调用激活/挂起接口
      this.$get('/updateSuspended',{
        processDefinitionId : row.id,
      }).then(res =>{
        if(res.code === 200){
          ElMessage.success('操作成功')
          this.fetchList()
        }else{
          ElMessage.error('操作失败')
        }
      }).catch(err =>{
        console.log(err)  
      })
    },
    // 查看详情
    viewDetail(row) {
      this.$router.push({
        name: 'ProcessDefinitionDetail',
        params: { id: row.id }
      })
    },
    // 过滤表单列表
    filterForm(query) {
      if (query) {
        this.filteredFormList = this.formList.filter(item => {
          return item.formName.toLowerCase().includes(query.toLowerCase())
        })
      } else {
        this.filteredFormList = this.formList
      }
    },
    // 获取表单列表
    async fetchFormList() {
      try {
        const data = {
          formName: ''
        }
        const res = await this.$post('/findFormConfig', data)
        if (res.code === 200) {
          this.formList = res.data
          this.filteredFormList = res.data // 初始化过滤后的列表
        } else {
          ElMessage.error('获取表单列表失败')
        }
      } catch (error) {
        console.error('获取表单列表失败:', error)
        ElMessage.error('获取表单列表失败')
      }
    },
    // 关闭表单配置对话框
    closeFormConfig() {
      this.formConfigDialogVisible = false
      // 重置表单配置
      this.formConfig = {
        processDefinitionId: '',
        formId: '',
        formJson: null
      }
    },
    // 表单选择变化
    async handleFormChange(formId) {
      // 先清空当前表单
      this.formConfig.formJson = null
      
      const selectedForm = this.formList.find(item => item.id === formId)
      if (selectedForm) {
        try {
          // 确保formJson是对象格式
          let formJson = selectedForm.formJson
          if (typeof formJson === 'string') {
            formJson = JSON.parse(formJson)
          }
          // 使用nextTick确保DOM更新后再设置formJson
          await this.$nextTick()
          this.formConfig.formJson = formJson
        } catch (error) {
          console.error('表单JSON解析失败:', error)
          ElMessage.error('表单格式错误，无法预览')
        }
      }
    },
    // 打开配置表单对话框
    openFormConfig(row) {
      this.currentRow = row
      this.formConfig = {
        processDefinitionId: row.id,
        formId: '',
        formJson: null
      }
      this.formConfigDialogVisible = true
      this.fetchFormList()
      // 如果已有配置，加载已有配置
      if (row.id) {
        this.loadExistingFormConfig(row.id)
      }
    },
    // 加载已有表单配置
    async loadExistingFormConfig(processDefinitionId) {
      try {
        const res = await this.$get('/getProcessForm', {
          id: processDefinitionId
        })
        if (res.code === 200 && res.data) {
          this.formConfig.formId = res.data.id
          try {
            // 确保formJson是对象格式
            let formJson = res.data.formJson
            if (typeof formJson === 'string') {
              formJson = JSON.parse(formJson)
            }
            this.formConfig.formJson = formJson
          } catch (error) {
            console.error('表单JSON解析失败:', error)
            ElMessage.error('表单格式错误，无法预览')
          }
        }
      } catch (error) {
        console.error('加载表单配置失败:', error)
      }
    },
    // 保存表单配置
    async saveFormConfig() {
      if (!this.formConfig.formId) {
        ElMessage.warning('请选择表单')
        return
      }

      try {
        // 确保保存时formJson是字符串格式
        const formJsonToSave = typeof this.formConfig.formJson === 'string' 
          ? this.formConfig.formJson 
          : JSON.stringify(this.formConfig.formJson)

        const res = await this.$get('/configureFormForProcessDefinition', {
          processDefinitionId: this.formConfig.processDefinitionId,
          formKey: this.formConfig.formId,
        })

        if (res.code === 200) {
          ElMessage.success('保存成功')
          this.formConfigDialogVisible = false
          this.fetchList() // 刷新列表
        } else {
          ElMessage.error(res.message || '保存失败')
        }
      } catch (error) {
        console.error('保存表单配置失败:', error)
        ElMessage.error('保存失败')
      }
    },
  },
  created() {
    // 初始化
    this.fetchList()
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.upload-demo {
  width: 100%;
}
.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}
.form-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  min-height: 200px;
  background-color: #f5f7fa;
}
</style> 